package com.mrogrape.notepad.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.URL;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

/**
 * 用来显示更新日志的对话框。
 * 
 * @author Ice Spring
 * @version 1.0
 *
 */
public class UpdateInfoDialog extends JDialog {

	/** serialVersionUID */
	private static final long serialVersionUID = 1L;

	private static final URL PATH = UpdateInfoDialog.class.getResource("/com/mrogrape/notepad/update.html");
	private JEditorPane contentView;
	private JPanel buttonPanel;
	private JButton okBtn;
	
	public UpdateInfoDialog(Frame owner){
		super(owner,true);
	
		initialize();
	}
	private void initialize() {
		
		this.setTitle("Update Logs");
		this.setMinimumSize(new Dimension(480,320));
		
		this.contentView = new JEditorPane();
		this.contentView.setEditable(false);
		getContentPane().add(new JScrollPane(this.contentView), BorderLayout.CENTER);
		
		this.buttonPanel = new JPanel();
		FlowLayout layout = (FlowLayout) this.buttonPanel.getLayout();
		layout.setAlignment(FlowLayout.RIGHT);
		getContentPane().add(this.buttonPanel, BorderLayout.SOUTH);
		
		this.okBtn = new JButton(this.action);
		this.buttonPanel.add(this.okBtn);
		
		try {
			this.contentView.setPage(UpdateInfoDialog.PATH);
		} catch (IOException e) {
			this.contentView.setText(getStackTraceText(e));
			e.printStackTrace();
		}
		
		this.pack();
		this.setLocationRelativeTo(this.getOwner());
	}
	
	private CloseAction action = new CloseAction();
	private class CloseAction extends AbstractAction{

		/**serialVersionUID */
		private static final long serialVersionUID = 1L;

		public CloseAction(){
			super.putValue(Action.NAME, "OK");
		}
		
		@Override
		public void actionPerformed(ActionEvent e) {
			setVisible(false);
			dispose();
		}
	}
	
	/**
	 * Returns a string representing the stack trace for this throwable.
	 *
	 * @param t The throwable.
	 * @return The stack trace.
	 */
	private static final String getStackTraceText(Throwable t) {
		
		StringBuffer buffer = new StringBuffer();
		buffer.append("Error to load logs: ");
		buffer.append(t.toString()).append("\n");
		StackTraceElement[] ste = t.getStackTrace();
		int count = ste.length;
		for (int i=0; i<count; i++) {
			buffer.append("    @ ").append(ste[i].toString()).
													append("\n");
		}
		return buffer.toString();
	}
	
	public static void main(String[] args){
		new UpdateInfoDialog(new JFrame()).setVisible(true);
	}
}
